/**
 * @author: XJC
 * @date: 2023-11-28 08:53
 * @description：operateSocket
 * @update: 2023-11-28 08:53
 */
import { setStorage, getStorage, clearStorage } from "@/utils/storage.manage.js"
import { getLogin,getUserInfo, getIsAdmin} from '@/utils/auth'

export default {
  data() {
    return {
      webSocket: null,
      lockReconnect: false, //是否真正建立连接
      connectStatus: false, //ws连接状态
      timeOnLine: 0,//计时
      timeOnce: null,//计算盘点时间，控制获取某一时间段内盘点数据
      serverTimeoutObj: null,//心跳检测定时器
      rfidNow: [],//存储当前盘点到的实物id数据
      bStyle:"color:#ffffff;background: linear-gradient(to right,#3b82f6,#06b6d4);padding:3px 5px;border-radius: 4px;",
      rStyle:"color:#ffffff;background: linear-gradient(to right,#ff0000,#f77669);padding:3px 5px;border-radius: 4px;",
    }
  },
  methods: {
    // 启用websocket
    initWebSocket() {
      console.log('%c正在初始化WebSocket...', this.bStyle)
      const wsUrl = process.env.VUE_APP_WS_PATH;
      //判断当前浏览器是否支持WebSocket
      if ("WebSocket" in window) {
        // 建立连接
        this.webSocket = new WebSocket(wsUrl);
      } else {
        this.$notify.error({
          title: '错误',
          message: '您的浏览器不支持websocket，请更换Chrome或者Firefox'
        });
        console.log('%c当前浏览器不支持建立WebSocket连接！！！！', this.rStyle)
        return;
      }
      //连接成功
      this.webSocket.onopen = this.websocketOnopen;
      //连接错误
      this.webSocket.onerror = this.websocketOnerror;
      //接收信息
      this.webSocket.onmessage = this.websocketOnmessage;
      //连接关闭
      this.webSocket.onclose = this.websocketOnclose;
    },
    reconnect() {
      // 重新连接
      console.log('%c WebSocket重新连接中...', this.bStyle)
      const that = this
      if (that.lockReconnect) {
        return;
      }
      that.lockReconnect = true;
      //没连接上会一直重连，设置延迟避免请求过多
      that.timeoutnum && clearTimeout(that.timeoutnum);
      that.timeoutnum = setTimeout(function () {
        //新连接
        that.initWebSocket();
        that.lockReconnect = false;
      }, 5000);
    },
    websocketOnopen() {
      let isLogin = getLogin()?"已登录":"未登录";
      let isAdmin = getIsAdmin()?"管理员":"普通用户";
      let user=JSON.parse(getUserInfo()||'{"nickName":"默认用户"}');
      let userName =user.nickName||'默认用户';
      //连接成功事件
      console.log('%c WebSocket连接成功！('+userName+'-'+isAdmin+'-'+isLogin+')', this.bStyle)
      this.connectStatus = true;
      //设置连接成功时当前时间戳
      this.timeOnLine = new Date().getTime();
      // this.confirmData();
      //开启心跳
      // this.start();
    },
    websocketOnerror(e) {
      //连接失败事件
      console.log('%c WebSocket连接发生错误！', this.rStyle,e)
      this.connectStatus = false;
      //重连
      this.reconnect();
    },
    websocketOnclose() {
      //连接关闭事件
      console.log('%c WebSocket连接关闭！', this.rStyle)
      this.connectStatus = false;
      //重连
      // this.reconnect();
    },
    // 开启心跳
    start() {
      console.log("开启心跳");
      const self = this;
      // let _num = 3;
      self.timeoutObj && clearInterval(self.timeoutObj);
      self.serverTimeoutObj && clearInterval(self.serverTimeoutObj);
      self.timeoutObj = setInterval(function () {
        //这里发送一个心跳，后端收到后，返回一个心跳消息，
        if (self.webSocket.readyState === 1) {
          //如果连接正常
          // console.log(self.webSocket);
          self.webSocket.send("heartCheck");
        } else {
          //否则重连
          // self.reconnect();
        }
      }, self.timeout);
    },
    // 重置心跳
    reset() {
      console.log("重置心跳");
      var that = this;
      //清除时间
      clearInterval(that.timeoutObj);
      clearInterval(that.serverTimeoutObj);
      //重启心跳
      // that.start();
    },


    confirmData() {
      this.timeOnce && clearTimeout(this.timeOnce);
      this.timeOnce = setTimeout(() => {
        if (new Date().getTime() - this.timeOnLine >= 2 * 60 * 1000) {
          //各种情况分析完成后，需对this.timeOnLine进行实时更新
          this.$server.commonApi.getIcodeList().then((res) => {
            let bookList = res.book;
            let bfInfo = res.bfinfo;
            let rfidN = this.rfidNow;
            //重置时间节点
            this.timeOnLine = new Date().getTime();

            //	存储盘点数据
            let timestamp = new Date().getTime();
            let arrstorage = getStorage("arrstorage") + '';
            let arr = [];
            if (arrstorage) {
              arr = arrstorage.split(',');
              arr.push(timestamp);
              setStorage(timestamp, rfidN.toString());
              while (arr.length > 30) {
                let oldid = arr.shift();
                clearStorage(oldid);
              }
            } else {
              arr = [timestamp];
              setStorage(timestamp, rfidN);
            }
            setStorage('arrstorage', arr.toString());


            //获取已报废但被盘点到的id，不做处理
            let bfRfid = rfidN.filter((item) => {
              bfInfo.includes(item)
            });

            //获取未报废的被盘点到的id
            let syRfid = rfidN.filter(item => {
              !bfRfid.includes(item)
            });


            //	先将盘点到的实物id和台账做对比
            let xtNopd = bookList.filter(item => {
              !syRfid.includes(item)
            });
            if (xtNopd.length > 0) {
              //	系统台账不在盘点数据内时（即存在系统无法识别的工器具）
            }
            let pdNoxt = syRfid.filter(item => {
              !bookList.includes(item)
            });
            if (pdNoxt.length > 0) {
              //	盘点的数据不在系统台账内时
            }

            //  将盘点的与历史盘点的进行对比
            //	获取存在台账中的盘点到的实物id
            let existRfid = rfidN.filter(item => {
              bookList.includes(item)
            });

            if (arr.length > 0 && arr.length == 1) {
              //继续盘点不执行任何操作，无法进行比对
              this.confirmData();
            } else {
              //	arr的长度大于1
              let late1Rfid = getStorage(arr[arr.length - 2]).split(',');
              //获取出库的实物id
              let chuid = late1Rfid.filter(item => {
                !existRfid.includes(item)
              });
              if (chuid.length > 0) {
                //	对出库的id进行出库流程操作
              }
              let ruid = existRfid.filter(item => {
                !late1Rfid.includes(item)
              })
              if (ruid.length > 0) {
                //	对入库id进行入库流程操作
              }
            }

          })
        } else {
          this.confirmData();
        }
      }, 1000 * 60);
    },

    websocketOnmessage(e) {
      //数据接收事件
      this.$eventBus.$emit("socketMsg", e);
    },

    sendSocketMsg(message) {
      if(this.webSocket.readyState !== WebSocket.OPEN) {
        console.log('%c连接未建立，还不能发送消息！', this.rStyle)
        return;
      }
      if(message) this.webSocket.send(message);
    },
    // 关闭websocket
    closeWebSocket() {
      if (this.webSocket){
        this.webSocket.close();
      }
    },
  },
  destroyed() {
    this.closeWebSocket();
  },

  beforeDestroy() {
    window.removeEventListener("beforeunload", this.closeWebSocket);
    this.$eventBus.$off("socketMsg");
  },
  created() {
    window.addEventListener("beforeunload", this.closeWebSocket);
  },
}
